<?php
/**
 * @author GhostWei
 * @date Aug 21, 2012
 */
class system_user_controller_special extends system_user_controller_panel {

	protected $concept = null;
	public function init() {
		if(!parent::init()) {
			return ;
		}
		picture_category::$_lang = $this->user->getLang();
		$this->concept = new picture_special_localeConcept($this->user->getLang());
		$this->_crumbs()->addPage(system_nav_page::create($this->language('Pictures'))->setRoute('picture/index'));
		$this->_crumbs()->addPage(system_nav_page::create($this->language('Specials'))->setRoute('picture/special/index'));
	}
	
	protected function _saveRow($row) {
		if(!$this->getRequest()->isPost()) {
			return $row;
		}		
		$manual = $this->_post('manualKeyNameCheck');
		if(!$row->getId() && !$manual) {
			$name = system_encrypt::createIdByTime();
		} else {
			$name = trim($this->_post('name'));
		}
		$row->getLocale()->setTitle(trim($this->_post('title')));
		$row->getLocale()->setDescription($this->_post('description'));
		$row->getLocale()->setContent($this->_post('content'));
		$this->view->manualKeyNameCheck = $manual ? true : false;
		$this->referer = $this->_post('referer');
		$this->view->categoryList = $categoryList = (array) $this->_post('category_id');
		$row->setName($name);
		$row->setDisplayOrder(intval($this->_post('display_order')));
		$row->setIsActive(intval($this->_post('is_active')) ? 1 : 0);
		$row->setKeywords(trim($this->_post('tag')));		
		foreach($categoryList AS $cid) {
			$row->addCategoryList($cid);
		}
		$this->_saveToDatabase($row, 'cover', 'image');
		return $row;
	}
	
	protected function _saveChanges() {
		if($this->getRequest()->isPost() && $this->_post('saveChange')) {
			try {
				$_keywords = (array) $this->_post('keyword');
				$_dorder = (array) $this->_post('_display_order');
				$_kwords = (array) $this->_post('_keyword');
				foreach((array) $this->_post('display_order') AS $id => $value) {
					$kv = isset($_keywords[$id]) ? $_keywords[$id] : '';
					if(isset($_dorder[$id]) && $_dorder[$id] == $value && isset($_kwords[$id]) && $_kwords[$id] == $kv) continue;
					if(!($row = $this->concept->fetch(array('id = ?' => $id)))) {
						continue;
					}
					$row->setDisplayOrder($value);
					$row->setKeywords((isset($_keywords[$id]) ? $_keywords[$id] : ''));
					try {
						$row->save();
					} catch (Exception $e) {
						$this->view->throwException = $e;
					}
				}
				$this->view->throwMessage = 'Complete';
			} catch (Exception $e) {
				$this->view->throwException = $e;
			}
		}
	}
	
	protected function _specialList($concept, $where = null) {
		$isRecommend = $concept == 'picture_special_recommend_concept';
		$adapter = new system_paginator_adapter_concept(new $concept($this->user->getLang()));
		$adapter->setCurrentPageNumber(intval($this->_param('page', 1)));
		if($where !== null) {
			$adapter->where($where);
		}
		if($isRecommend) {
			$this->view->group_id = $group_id = intval($this->_get('group_id'));
			if($group_id) {
				$adapter->where("recommend.group_id = '$group_id'");
			}
		}
		$this->view->order = $order = strtolower($this->_get('order'));
		$this->view->searchby = $searchby = strtolower($this->_get('searchby'));
		$this->view->category_id = $category_id = intval($this->_get('category_id'));
		if($category_id) {
			$adapter->where(array('special.id IN(SELECT `special_id` FROM `picture_special_category` WHERE `category_id` = ?)' => $category_id));
		}
		if(1 && $k = trim($this->_get('k'))) {
			$adapter->where("special.id IN(SELECT `special_id` FROM `picture_special_keyword` WHERE `keyword_id` IN(SELECT `id` FROM `resource_keyword` WHERE `name` = ?))", $k);
		}
		if(1 && $this->_get('filter') == 'isolated') {
			$adapter->where("special.id NOT IN(SELECT `special_id` FROM `picture_special_category` WHERE `lang` = '{$this->user->getLang()}')");
		}
		$keyword = trim($this->_get('keyword'));
		if($keyword == self::$_keyword) $keyword = '';
		if($keyword) {
			$keyword = addslashes($keyword);
			$in = "SELECT `special_id` FROM `picture_special_locale` WHERE `title` LIKE '%$keyword%' AND `lang` = '{$this->user->getLang()}'";
			$adapter->where("`name` LIKE '%$keyword%' OR `id` IN($in)");
		}
		$_order = array("is_active DESC", "display_order ASC", "id DESC");
		if($order) {
			$this->view->sort = $sort = intval($this->_get('sort'));
			switch($order) {
				case 'date': {
					$order = 'lastmodified';
					break;
				}
				case 'photo': {
					$order = 'ptotal';
					break;
				}
				case 'creationtime': {
					break;
				}
				default: {
					$sort = !$sort;
					$order = 'display_order';
					break;
				}
			}
			$_sort = !$sort ? 'DESC' : 'ASC';
			$_order = array("$order $_sort");
		}
		$adapter->setLimit(30);
		$adapter->order($_order);
		$list = new system_paginator($adapter);
		
		$sids = $categories = $keywords = array();
		foreach($list AS $row) {
			$sids[$row->getId()] = $row->getId();
		}
		if(!empty($sids)) {
			$pid = implode(', ', $sids);
			$sql = "";
			$sql .= "SELECT a.`special_id`, b.`category_id`, b.`title` FROM `picture_category_locale` AS b ";
			$sql .= "INNER JOIN `picture_special_category` AS a ON a.`category_id` = b.`category_id` ";
			$sql .= "WHERE a.`special_id` IN($pid) AND b.`lang` = '{$this->user->getLang()}' AND a.`lang` = '{$this->user->getLang()}'";
			foreach(system_db::getAdapter()->fetchAll($sql) AS $row) {
				$categories[$row['special_id']][] = $row;
			}
			$sql = "";
			$sql .= "SELECT a.`special_id`,a.`keyword_id`,b.`name` FROM `picture_special_keyword` AS a ";
			$sql .= "INNER JOIN `resource_keyword` AS b ON a.`keyword_id` = b.`id` ";
			$sql .= "WHERE a.`special_id` IN($pid) AND b.`lang` = '{$this->user->getLang()}'";
			foreach(system_db::getAdapter()->fetchAll($sql) AS $row) {
				$keywords[$row['special_id']][] = $row;
			}
		}
		$rgConcept = new picture_special_regroup_concept($this->user->getLang());
		$regroups = array();
		foreach($rgConcept->fetchAll() AS $group) {
			$regroups[$group->getId()] = $group;
		}
		if($isRecommend) {
			$gn = isset($regroups[$group_id]) ? $regroups[$group_id]->getDescription() : $this->language('List All');
			$this->_crumbs()->addPage(system_nav_page::create($gn)->setRoute('picture/special/recommend', array(), array('group_id' => $group_id)));
		}
		
		$this->view->regroups = $regroups;
		$this->view->categories = $categories;
		$this->view->keywords = $keywords;
		$this->view->list = $list;
	}

}
